package com.qf.FinancialManagement.service.Impl;

import com.qf.FinancialManagement.domain.TmsStatementCc;
import com.qf.FinancialManagement.mapper.TmsStatementCcMapper;
import com.qf.FinancialManagement.service.TmsStatementCcService;
import com.qf.common.utils.SecurityUtils;
import com.qf.common.utils.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * ---好运常在---
 *
 * @author ChengShuaiKe
 * @date 2025/9/2 0002
 * @desc
 */
@Service
public class TmsStatementCcServiceImpl implements TmsStatementCcService {
    // 添加日志对象声明（关键修复）
    private static final Logger log = LoggerFactory.getLogger(TmsStatementCcServiceImpl.class);

    @Autowired
    private TmsStatementCcMapper tmsStatementCcMapper;

    @Override
    public List<TmsStatementCc> selectStatementList(TmsStatementCc tmsStatementCc) {
        // 处理结束日期，确保包含当天的所有数据
        if (tmsStatementCc.getEndCreateTime() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(tmsStatementCc.getEndCreateTime());
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            tmsStatementCc.setEndCreateTime(calendar.getTime());
        }

        return tmsStatementCcMapper.selectStatementList(tmsStatementCc);
    }

    @Override
    public String importStatementList(List<TmsStatementCc> statementList, boolean updateSupport) {
        if (StringUtils.isEmpty(statementList)) {
            throw new RuntimeException("导入数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (TmsStatementCc statement : statementList) {
            try {
                // 1. 检查是否已存在（根据对账单号唯一标识）
                TmsStatementCc existing = tmsStatementCcMapper.selectByStatementNo(statement.getStatementNo());
               // 数据预处理：确保 customer 字段不为空
                if (statement.getCustomer() == null || statement.getCustomer().trim().isEmpty()) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、对账单 " + statement.getStatementNo() + " 导入失败：客户信息不能为空";
                    failureMsg.append(msg);
                    log.error(msg);
                    continue;
                }


                if (existing == null) {
                    // 2. 新增：设置默认值（创建人、时间等）
                    statement.setCreator(SecurityUtils.getUsername()); // 当前登录用户
                    statement.setCreateTime(new Date());
                    statement.setUpdateTime(new Date());
                    tmsStatementCcMapper.insert(statement);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、对账单 " + statement.getStatementNo() + " 导入成功");
                } else if (updateSupport) {
                    // 3. 更新：仅更新可编辑字段（避免覆盖创建人等）
                    statement.setId(existing.getId()); // 保留原ID
                    statement.setCreator(existing.getCreator()); // 保留原创建人
                    statement.setCreateTime(existing.getCreateTime()); // 保留原创建时间
                    statement.setUpdateTime(new Date()); // 更新修改时间
                    tmsStatementCcMapper.updateById(statement);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、对账单 " + statement.getStatementNo() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、对账单 " + statement.getStatementNo() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、对账单 " + statement.getStatementNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        // 构建返回消息
        if (failureNum > 0) {
            failureMsg.insert(0, "导入失败：");
            throw new RuntimeException(failureMsg.toString() + successMsg);
        } else {
            successMsg.insert(0, "导入成功！共 " + successNum + " 条数据：");
            return successMsg.toString();
        }
    }
}
